<template>
  <div>
    <el-form ref="wyform" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
      </el-form-item>
      
       <el-form-item>
         <el-button type="success" size="small" plain @click="save">保存</el-button>
       </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { post, get, asyncRequest } from '@/plugins/axios'
export default {
  name: 'CategoryEdit',
  props: ['id', 'module','parentId','level'],
  created () {
    if (this.id) {
      this.getone()
    }else {
		this.form.parentId = this.parentId
		this.form.level = this.level
	}
  },
  data () {
    const checkData = async (rule, value, callback) => {
      const response = await asyncRequest(this.module + '/check', 'get', { value: value, id: this.id })
      if (response.data.obj) {
        callback()
      } else {
        callback(new Error('已经存在相同数据'))
      }
    }
    return {
      url: {
        add: this.module + '/add',
        update: this.module + '/update',
        getone: this.module + '/getone'
      },
      form: {
        name: '',
        parentId:null,
		level:null
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { max: 20, message: '分类名称最多10个字符', trigger: 'blur' }
        ],
        
      }
    }
  },
  methods: {
    save () {
      // 先验证整个表单 如果有一个不通过都不能提交post请求
      this.$refs.wyform.validate((valid) => {
        if (valid) {
          post(this.id ? this.url.update : this.url.add, this.form, response => {
            this.$emit('update:show', false)
            this.$emit('getTableData')
          })
        }
      })
    },
    getone () {
      get(this.url.getone, { id: this.id }, response => {
        for (const key in this.form) {
          this.form[key] = response[key]
        }
        this.form.id = response.id
        this.fileList.push({
          name: response.icon,
          url: this.img(response.icon)
        })
      })
    },
    changeIcon (file) {
      this.form.file = file.raw
    },
    removeIcon () {
      this.form.file = null
    }
  }
}
</script>

<style scoped lang="less">
</style>
